package com.asimplefox.controllers;

import com.asimplefox.configs.FileConfig;
import com.asimplefox.entity.Vid;
import com.asimplefox.entity.VidHistory;
import com.asimplefox.entity.VidList;
import com.asimplefox.serurity.UserRoleDetails;
import com.asimplefox.service.IVidHistoryService;
import com.asimplefox.service.IVidService;
import com.asimplefox.service.abst.ResultU;
import com.asimplefox.service.impl.VidListServiceImpl;
import io.github.kloping.judge.Judge;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.ExecutorService;

/**
 * <br>	`vid` INT(11) NOT NULL COMMENT '所属列表id',
 * <br>    `st` INT(11) NOT NULL COMMENT '所属列表排序',
 * <br>    `st_name` VARCHAR(50) NULL DEFAULT NULL COMMENT '第n集/话',
 * <br>    `url` VARCHAR(255) NOT NULL,
 * <br>    `astrict` VARCHAR(50) NULL DEFAULT NULL,
 *
 * @author github.kloping
 */
@RestController
@RequestMapping("/api/video")
@Slf4j
public class VidController implements ResultU {
    @Autowired
    IVidService vidService;
    @Autowired
    private VidListServiceImpl vidListServiceImpl;

    @RequestMapping("/offer")
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public String offer(@RequestParam("vid") Integer vid, @RequestParam("st") Integer st,
                        @RequestParam(value = "st_name", required = false) String st_name,
                        @RequestParam(value = "astrict", required = false, defaultValue = "false") String astrict,
                        @RequestParam("file") MultipartFile file, HttpServletResponse response) {
        if (Judge.isEmpty(st_name)) st_name = "第" + st + "集";
        Vid vid0 = new Vid().setVid(vid).setSt(st).setStName(st_name).setAstrict(Boolean.valueOf(astrict));
        return vidService.save(vid0, file, response);
    }

    @Autowired
    IVidHistoryService vidHistoryService;

    @Autowired
    ExecutorService executorService;

    @RequestMapping("/list")
    public Object list(@AuthenticationPrincipal UserRoleDetails details
            , @RequestParam("vid") Integer vid) {
        executorService.submit(() -> {
            try {
                //提交用户历史记录
                if (details != null) {
                    //查询用户历史记录已存在12条的话则删除最久的一条记录
                    VidHistory vidHistory = new VidHistory();
                    vidHistory.setVid(vid).setUid(details.getUser().getId());
                    VidHistory vh0 = vidHistoryService.lambdaQuery(vidHistory).one();
                    if (vh0 == null) {
                        //查询视频列表 设置封面
                        VidList vl = vidListServiceImpl.lambdaQuery().eq(VidList::getId, vid).one();
                        vidHistory.setTime(System.currentTimeMillis());
                        vidHistory.setSurl(vl.getIcon());
                        vidHistory.setFtype(vl.getFtype());
                        vidHistory.setVname(vl.getName());
                        Integer count = vidHistoryService.lambdaQuery().eq(VidHistory::getUid, details.getUser().getId())
                                        .count().intValue();
                        if (count >= 12) {
                            vidHistoryService.lambdaUpdate()
                                    .eq(VidHistory::getUid, details.getUser().getId())
                                    .orderByAsc(VidHistory::getTime).last("LIMIT 1")
                                    .remove();
                        }
                        vidHistoryService.save(vidHistory);
                    } else {
                        vidHistoryService.lambdaUpdate()
                                .eq(VidHistory::getUid, details.getUser().getId())
                                .eq(VidHistory::getVid, vid)
                                .set(VidHistory::getTime, System.currentTimeMillis()).update();
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
        return vidService.lambdaQuery()
                .eq(Vid::getVid, vid)
                .select(Vid::getId, Vid::getVid, Vid::getSt, Vid::getStName, Vid::getUrl, Vid::getAstrict)
                .orderByAsc(Vid::getSt).list();
    }

    @Autowired
    FileConfig fileConfig;

    @RequestMapping("/del")
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object del(@RequestParam("id") Integer id) {
        Vid vid = vidService.getById(id);
        if (vid == null) return fail("未发现对应视频");
        else {
            fileConfig.del(vid.getUrl());
            return vidService.removeById(id) ? success("删除成功") : fail("删除失败");
        }
    }
}
